package spring.cloud.tasks.executor.executor.task.task_item_allot;

import lombok.Getter;
import lombok.Setter;
import spring.cloud.tasks.executor.executor.Executor;
import spring.cloud.tasks.executor.executor.task.TaskExecuteEngine;
import spring.cloud.tasks.executor.executor.task.TaskExecutor;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Setter
@Getter
public class ExecutorTaskTriggerTask implements Runnable {
    private String executorId;
    private Executor executor;

    public ExecutorTaskTriggerTask(String executorId) {
        this.executorId = executorId;
        this.executor = null;
    }

    @Override
    public synchronized void run() {
        Map<String, TaskExecuteDate> taskIdToTaskExecuteDateMap = new HashMap<String, TaskExecuteDate>();
        Map<String, TaskExecutor> taskIdToTaskExecutorMap = this.executor.taskIdToTaskExecutorMap.removeAndGetTaskIdToTaskExecutorMap();
        if (taskIdToTaskExecutorMap == null) {
            return;
        }
        Date nowDate = new Date();
        Iterator<String> iterator = taskIdToTaskExecutorMap.keySet().iterator();
        while (iterator.hasNext()) {
            final String taskId = iterator.next();
            TaskExecuteDate taskExecuteDate = taskIdToTaskExecuteDateMap.get(taskId);
            if (taskExecuteDate != null) {
                for (Date date : taskExecuteDate.getDateList()) {
                    //还没有到执行时间点
                    if (nowDate.getTime() < date.getTime()) {
                        break;
                        //刚刚过了时间点
                    } else if (nowDate.getTime() >= date.getTime() && date.getTime() > nowDate.getTime() - 1000 * 15) {
                        taskExecuteDate.getDateList().remove(date);
                        final TaskExecutor taskExecutor = taskIdToTaskExecutorMap.get(taskId);
                        if (taskExecutor != null) {
                            TaskExecuteEngine taskExecuteEngine = taskExecutor.getTaskExecuteEngine();
                            Thread thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    taskExecuteEngine.startTaskItemExecuteThread();
                                }
                            });
                            thread.start();
                        }
                        break;
                    } else {
                        //超过执行时间很久了
                        taskExecuteDate.getDateList().remove(date);
                    }

                }
            }
            continue;

        }
    }
}
